﻿using Entity;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using ProdService;
using ViewModels.JsonResult;
using ViewModels.LogOn;
using ViewModels.Shared;
using ViewModels.User;

namespace UI.ApiControllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class LogOnController : BaseController
    {
        public LogOnController(PhoneService phoneService, UserService userService)
            : base(userService, phoneService)
        {
        }

        [HttpPost]
        [Route(nameof(_SMS))]
        public WithError _SMS([FromForm] PhoneModel model, bool remember = false)
        {
            Phone phone = phoneService.GetBy(model.Number);
            WithError result = checkSMS(model, phone);

            if (result.Errors.Count > 0)
            {
                return result;
            }

            userService.On(phone.User.Id, remember);

            result.Succeed = true;
            return result;
        }

        [HttpPost]
        [Route(nameof(_Pwd))]
        public WithError _Pwd([FromForm] LogonModel model, bool remember = false)
        {
            WithError result = checkCaptcha(model.Captcha);
            if (result.Errors.Count > 0)
            {
                return result;
            }

            User user = userService.GetByName(model.PhoneNumberOrName);
            if (user == null)
            {
                Phone phone = phoneService.GetBy(model.PhoneNumberOrName);
                if (phone == null)
                {
                    result.Errors.Add(nameof(model.PhoneNumberOrName), "* 手机号码或用户名不存在");
                    return result;
                }
                if (phone.User == null)
                {
                    result.Errors.Add(nameof(model.PhoneNumberOrName), "* 手机号码尚未注册");
                    return result;
                }
                user = phone.User;
            }//else nothing

            if (string.IsNullOrEmpty(user.Password))
            {
                result.Errors.Add(nameof(model.Password), "* 该账号还没有设置密码");
                return result;
            }
            if (!userService.IsPasswordCorrect(user, model.Password))
            {
                result.Errors.Add(nameof(model.Password), "* 用户名或密码错误");
                return result;
            }

            userService.On(user.Id, remember);

            result.Succeed = true;
            return result;
        }

    }
}
